package com.imdroid.carac.services;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.telephony.SmsMessage;
import android.util.Log;

import com.imdroid.carac.IMDroid;
import com.imdroid.carac.R;

/**
 * The monitor of the SMS
 * 
 */
public class SMSReceiver extends BroadcastReceiver {
	private static final String TAG = "SMSReceiver";
	/**
	 * The action of telephony sms
	 */
	private static final String ACTION = "android.provider.Telephony.SMS_RECEIVED";

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.content.BroadcastRe
	 * ceiver#onReceive(android.content.Context, android.content.Intent)
	 */
	public void onReceive(Context context, Intent intent) {
		if (intent != null && intent.getAction() != null
				&& ACTION.compareToIgnoreCase(intent.getAction()) == 0) {
			Log.e(TAG, "Receive SMS ---");
			Object[] pduArray = (Object[]) intent.getExtras().get("pdus");
			SmsMessage[] messages = new SmsMessage[pduArray.length];

			for (int i = 0; i < pduArray.length; ++i) {
				messages[i] = SmsMessage.createFromPdu((byte[]) pduArray[i]);

				if (messages[i] != null
						&& messages[i].getDisplayMessageBody() != null
						&& messages[i].getDisplayMessageBody().trim().length() > 0)
					process(messages[i]);
			}
		}

	}

	/**
	 * Process the notification come from SMS
	 * 
	 * @param smsCommand
	 *            the command of SMS
	 */
	private void process(SmsMessage smsCommand) {

		// 判断是否为信息有效性
		String wholeMessage = smsCommand.getDisplayMessageBody();
		Log.d("Command", wholeMessage);
		if (wholeMessage == null || wholeMessage.trim().length() <= 0)
			return;

		// 截取后面的真实信息
		if (!wholeMessage.startsWith("IMD##")) {
			Log.d(TAG, "Invalid SMS message");
			return;
		}
		
		//发出提示声
		MediaPlayer mp = MediaPlayer.create(IMDroid.getContext(),
				R.raw.tip_ding_dong);
		mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
			public void onCompletion(MediaPlayer mp) {
				mp.release();
			}
		} );
		mp.start();

		int start = wholeMessage.indexOf("IMD##", 0) + "IMD##".length();
		int end = wholeMessage.indexOf("##", "IMD##".length());
		String command = null;
		if (end > 0)
			command = wholeMessage.substring(start, end);
		else
			command = wholeMessage.substring(start, wholeMessage.length());

		// 发送信息
		NotificationHandler eventHandler = NotificationService
				.getNotificationHandler();
		eventHandler.obtainMessage(NotificationService.RECEIVED, command)
				.sendToTarget();
	}
}
